package com.liao.ticket.common.handler;

import com.alibaba.fastjson.JSON;
import com.liao.ticket.common.exception.ErrorCode;
import com.liao.ticket.dao.dos.ViewManager;
import com.liao.ticket.dao.pojo.User;
import com.liao.ticket.service.LoginService;
import com.liao.ticket.service.UserService;
import com.liao.ticket.util.AdminThreadLocal;
import com.liao.ticket.util.AirlineThreadLocal;
import com.liao.ticket.util.AirportThreadLocal;
import com.liao.ticket.util.UserThreadLocal;
import com.liao.ticket.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在执行controller方法(Handler)之前执行
        /**
         * 1.需要判断 请求 接口路径 是否为 HandlerMethod (controller 方法)
         * 2.判断 token 是否为空，如果为空 未登录
         * 3.如果 token 不为空，登录验证 loginService checkToken
         * 4.如果认证成功 放行
         */
        if (!(handler instanceof HandlerMethod)) {
            // handler 可能是 RequestResourceHandler springboot 程序 访问静态资源 默认去classpath 下的 static 目录去查询
            return true;
        }
        String token = request.getHeader("token");
        log.info("======================== start =============================");
        log.info("request uri:{}", request.getRequestURI());
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("======================== end =============================");
        if (StringUtils.isBlank(token)) {
            Result result = Result.fail(ErrorCode.USER_NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        User user = loginService.checkToken(token);
        if (user == null) {
            Result result = Result.fail(ErrorCode.USER_NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        Integer type = user.getType();
        if(type != 10){
            ViewManager viewManager = userService.selectManagerByIdAndType(user.getId(), user.getType());
            if(viewManager != null){
                if (type == 20){
                    AirportThreadLocal.put(viewManager);
                }else if(type == 30){
                    AirlineThreadLocal.put(viewManager);
                }
            }
            if(type == 0){
                AdminThreadLocal.put(user);
            }
        }
        UserThreadLocal.put(user);
        // 认证成功，放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 如果不删除 ThreadLocal 中用完的信息 会有内存泄露风险
        UserThreadLocal.remove();
        AdminThreadLocal.remove();
        AirportThreadLocal.remove();
        AirlineThreadLocal.remove();
    }
}
